package com.github.xiaoymin.map.ext;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.github.xiaoymin.map.MapClientConfig;
import com.github.xiaoymin.map.common.MapClientConstants;
import com.github.xiaoymin.map.model.BaiduKey;
import com.github.xiaoymin.map.model.BaiduLocation;
import com.github.xiaoymin.map.request.baidu.BaiduCoordTranslateRequest;
import com.github.xiaoymin.map.request.baidu.BaiduGenCoderRequest;
import com.github.xiaoymin.map.response.baidu.BaiduGenCoderResponse;
import com.github.xiaoymin.map.response.baidu.BaiduIpLocationResponse;
import com.github.xiaoymin.map.util.GsonUtils;
import com.github.xiaoymin.map.util.XmlUtils;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.Optional;

public class BaiduClient extends BaiduAbstractClient{

    Logger logger= LoggerFactory.getLogger(BaiduClient.class);
    /**
     * 根据开发配置构造MapClient
     *
     * @param mapClientConfig 开发配置
     */
    public BaiduClient(MapClientConfig mapClientConfig) {
        super(mapClientConfig);
    }

    /**
     * 根据经纬度查询用户的详细地址
     * 百度地图逆地址API:http://api.map.baidu.com/reverse_geocoding/v3/
     * @param baiduGenCoderRequest 参数
     * @return
     */
    public Optional<BaiduGenCoderResponse> getCoder(BaiduGenCoderRequest baiduGenCoderRequest){
        assertNotEmpty(baiduGenCoderRequest,"逆地理编码API请求对象不能为空");
        String getBaiduKey = mapClientConfig.getBaiduKey();
        BaiduKey baiduKey = new BaiduKey(getBaiduKey);
        String api= MapClientConstants.BAIDU_API_REGEO+parameter(appendKey(baiduGenCoderRequest.toMap(),baiduKey));
        logger.info("逆地理编码API:{}",api);
        HttpGet get=new HttpGet(api);
        String execute = execute(get);
        BaiduGenCoderResponse baiduGenCoderResponse = (BaiduGenCoderResponse) XmlUtils.convertXmlStrToObject(BaiduGenCoderResponse.class, execute);
        if(baiduGenCoderResponse!=null&&StrUtil.equals(baiduGenCoderResponse.getStatus(),"0")){
            return Optional.ofNullable(baiduGenCoderResponse);
        }
        return Optional.empty();
    }

    /**
     * 坐标转换http://api.map.baidu.com/geoconv/v1/?
     * @param baiduCoordTranslateRequest 参数
     * @return
     */
    public List<BaiduLocation> getCoordConvert(BaiduCoordTranslateRequest baiduCoordTranslateRequest){
        assertNotEmpty(baiduCoordTranslateRequest,"坐标转换参数不能为空");
        String getBaiduKey = mapClientConfig.getBaiduKey();
        BaiduKey baiduKey = new BaiduKey(getBaiduKey);
        String api= MapClientConstants.BAIDU_API_COORD_CONVER+parameter(appendKey(baiduCoordTranslateRequest.toMap(),baiduKey));
        logger.info("坐标转换API:{}",api);
        HttpGet get=new HttpGet(api);
        JsonObject jsonObject = responseSuccess(get);
        if(jsonObject!=null){
            JsonElement locations = jsonObject.get("result");
            GsonBuilder gsonBuilder=new GsonBuilder();
            List<BaiduLocation> mapLocations = gsonBuilder.create().fromJson(locations, new TypeToken<List<BaiduLocation>>() {}.getType());
            if(CollectionUtil.isNotEmpty(mapLocations)){
                return mapLocations;
            }
        }
        return null;
    }

    /**
     * 根据IP地址获取 用户的详细地址和经纬度  http://api.map.baidu.com/location/ip?
     * @param ip
     * @return
     */
    public Optional<BaiduIpLocationResponse> ipLocation(String ip){
        String getBaiduKey = mapClientConfig.getBaiduKey();
        BaiduKey baiduKey = new BaiduKey(getBaiduKey);
        Map<String,String> params= MapUtil.builder("ip",ip).build();
        String api = MapClientConstants.BAIDU_API_IP_LOCATION + parameter(appendKey(params, baiduKey));
        logger.info("IP地理位置定位API:{}",api);
        HttpGet get=new HttpGet(api);
        JsonObject jsonObject = responseSuccess(get);
        if(jsonObject!=null){
            JsonElement content = jsonObject.get("content");
            GsonBuilder gsonBuilder=new GsonBuilder();
            BaiduIpLocationResponse baiduIpLocationResponse = gsonBuilder.create().fromJson(content, BaiduIpLocationResponse.class);
            return Optional.ofNullable(baiduIpLocationResponse);
        }
        return Optional.empty();

    }

    /**
     * 百度地图的返回成功标志处理返回json
     * @param httpRequest 请求
     * @return 成功后的JsonObject对象
     */
    protected JsonObject responseSuccess(HttpUriRequest httpRequest){
        String content=execute(httpRequest);
        if (StrUtil.isNotBlank(content)) {
            JsonElement jsonElement = jsonParser.parse(content);
            if (jsonElement != null && jsonElement.isJsonObject() && jsonElement.getAsJsonObject() != null) {
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                String status = GsonUtils.getString(jsonObject, "status");
                if (StrUtil.equals(status, MapClientConstants.BAIDU_RESPONSE_SUCCESS)) {
                    //成功
                    return jsonObject;
                }else{
                    logger.error("<==============百度地图请求接口失败==============>");
                }
            }
        }
        return null;
    }
}
